package threecard.android;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;

public class Login extends Activity implements OnClickListener {

	public ProgressDialog progressDialog;
	private EditText userEditText;
	private EditText passEditText;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);

		// Progress bar.
		
		progressDialog = new ProgressDialog(this);
		// TODO: use a string in resource instead of this.
		progressDialog.setMessage("Please wait ...");
		progressDialog.setIndeterminate(true);
		progressDialog.setCancelable(true);
		
		
		// initialize to EditText: userEditText and passEditText.
		userEditText = (EditText) findViewById(R.id.username);
		passEditText = (EditText) findViewById(R.id.password);

		View loginButton = findViewById(R.id.login_login_button);
		loginButton.setOnClickListener(this);

		View cancelButton = findViewById(R.id.login_cancel_button);
		cancelButton.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.login_login_button:
			int usersize = userEditText.getText().length();
			int passsize = passEditText.getText().length();

			// First check the validity of the username and password.
			if (usersize > 0 && passsize > 0) {
				progressDialog.show(); // Show progress dialog.
				String user = userEditText.getText().toString(); // get username.
				String pass = passEditText.getText().toString(); // get password.
				doLogin(user, pass); // process username and password.
			} else {
				// The user did not enter either username or password.
				// Display an error message.
				createDialog("Error", "Please enter Username and Password");
			}
			break;

		case R.id.login_cancel_button:
			setResult(RESULT_CANCELED);
			finish();
		default:
			break;
		}

	}

	private void createDialog(String title, String text) {
		AlertDialog ad = new AlertDialog.Builder(this)
				.setPositiveButton("Ok", null).setTitle(title).setMessage(text)
				.create();

		ad.show();
	}

	//TODO: implement login process
	private void doLogin(String user, String pass) {
		// Try with out md5 first
		/*
		final String pw = md5(pass);
		AlertDialog ad = new AlertDialog.Builder(this)
		.setPositiveButton("OK", null).setTitle("Login information")
		.setMessage("Username: " + user + "\nPassword (encrypted): " + pw)
		.create();
		ad.show();*/
		Log.i("get u & p","ok");
		postData(user,pass);
		
	}
	
	//Need  change 192.168.1.10 to your local IP address, 
	public void sendData(ArrayList<NameValuePair> data) {
	     // 1) Connect via HTTP. 2) Encode data. 3) Send data.
	    try
	    {
	        HttpClient httpclient = new DefaultHttpClient();
	        HttpPost httppost = new HttpPost("http://192.168.1.10/3cards/script.php");
	        httppost.setEntity(new UrlEncodedFormEntity(data));
	        String showlog = data.toString();
	        Log.i("show data",showlog);
	        HttpResponse response = httpclient.execute(httppost);
	        Log.i("postData", response.getStatusLine().toString());
	            //Could do something better with response.
	    }
	    catch(Exception e)
	    {
	        Log.e("log_tag", "Error:  "+e.toString());
	    }  
	}
	
	public void postData (String username, String password) {
	    //Add data to be send.
	    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
	    nameValuePairs.add(new BasicNameValuePair("username",username));
	    nameValuePairs.add(new BasicNameValuePair("password",password));
	    Log.i("set data","ok");
	    this.sendData(nameValuePairs);
	}
	
	// read from reponse to string
	public String inputStreamToString(InputStream is) throws IOException {
	    String s = "";
	    String line = "";
	    
	    // Wrap a BufferedReader around the InputStream
	    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
	    
	    // Read response until the end
	    while ((line = rd.readLine()) != null) { s += line; }
	    
	    // Return full string
	    return s;
	}

	
	/** A md5 code from the internet !*/
	private String md5(String pass) {
		  MessageDigest digest;
	        try {
	            digest = MessageDigest.getInstance("MD5");
	            digest.reset();        
	            digest.update(pass.getBytes());
	            byte[] a = digest.digest();
	            int len = a.length;
	            StringBuilder sb = new StringBuilder(len << 1);
	            for (int i = 0; i < len; i++) {
	                sb.append(Character.forDigit((a[i] & 0xf0) >> 4, 16));
	                sb.append(Character.forDigit(a[i] & 0x0f, 16));
	            }
	            return sb.toString();
	        } catch (NoSuchAlgorithmException e) { e.printStackTrace(); }
	        return null;
	}

}
